"use client";

import Image from 'next/image';
import CheckCircleIcon from "@/assets/icons/check-circle.svg";
import ArrowUpRightIcon from "@/assets/icons/arrow-up-right.svg";
import { SectionHeader } from '../components/SectionHeader';
import { Card } from "@/components/Card";
import { useEffect, useState } from 'react';
import { getHomeData, getProjects } from '@/lib/api';
import type { HomeData, Project } from '@/lib/api';
import { LoadingSpinner } from "@/components/ui/loading";
import { motion } from 'framer-motion';
import { getImageUrl } from '@/lib/utils';

export const ProjectsSection = () => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [homeData, setHomeData] = useState<HomeData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const [projectsData, homeResponse] = await Promise.all([
          getProjects(),
          getHomeData()
        ]);

        setProjects(projectsData);
        setHomeData(homeResponse);
      } catch (error) {
        console.error('Error fetching data:', error);
        setError('加载数据失败，请稍后重试');
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  if (isLoading) {
    return (
      <section id="projects" className="pb-16 lg:py-24">
        <div className="container">
          <SectionHeader 
            eyebrow="Real-world Results" 
            title="Loading..."
            description="Loading..."
          />
          <div className="mt-12 lg:mt-20 flex justify-center">
            <LoadingSpinner />
          </div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section id="projects" className="pb-16 lg:py-24">
        <div className="container">
          <SectionHeader 
            eyebrow="Real-world Results" 
            title="Error"
            description={error}
          />
        </div>
      </section>
    );
  }

  return (
    <section id="projects" className="pb-16 lg:py-24">
      <div className="container">
        <SectionHeader 
          eyebrow={homeData?.my_work || ''}
          title={homeData?.work_title || ''}
          description={homeData?.work_description || ''}
        />
        
        <div className="flex flex-col mt-10 gap-20 md:mt-20">
          {projects.map((project, index) => (
            <motion.div
              key={project.documentId}
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ 
                once: true,
                amount: 0.3,
                margin: "-10% 0px -10% 0px"
              }}
              transition={{ 
                duration: 0.4,
                delay: index * 0.1,
                ease: [0.1, 0.3, 0.2, 1]
              }}
              className="will-change-transform"
              style={{
                transform: 'translate3d(0,0,0)',
                backfaceVisibility: 'hidden'
              }}
            >
              <Card 
                className="pt-8 px-8 pb-0 md:pt-12 md:px-10 lg:pt-16 lg:px-20 sticky top-16 transform-gpu"
                style={{
                  top: `calc(64px + ${index * 40}px)`,
                  willChange: 'transform',
                  perspective: '1000px'
                }}
              >
                <div className="lg:grid lg:grid-cols-2 lg:gap-16">
                  <div className="lg:pb-16">
                    <div className="flex">
                      <div className="bg-gradient-to-r from-emerald-300 to-sky-400 inline-flex gap-2 font-bold uppercase tracking-widest text-sm text-transparent bg-clip-text">
                        <span>{project.who}</span>
                        <span className="mx-2">&bull;</span>
                        <span>{project.year}</span>
                      </div>
                    </div>
                    <h3 className="font-serif text-2xl mt-2 md:mt-5 md:text-4xl">{project.title}</h3>
                    <hr className="border-t-2 border-white/5 mt-4 md:mt-5" />
                    <ul className="flex flex-col gap-4 mt-4 md:mt-5"> 
                      {project.results.map((result, index) => (
                        <motion.li
                          key={`${project.documentId}-result-${index}`}
                          initial={{ opacity: 0, x: -20 }}
                          whileInView={{ opacity: 1, x: 0 }}
                          viewport={{ once: true }}
                          transition={{ 
                            duration: 0.3,
                            delay: 0.3 + index * 0.1
                          }}
                          className="flex gap-2 text-sm md:text-base text-white/50"
                        >
                          <CheckCircleIcon className="size-5 md:size-6" />
                          <span>{result.title}</span>
                        </motion.li>
                      ))}
                    </ul>
                    <motion.a
                      href={project.link}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                    >
                      <button className="bg-white text-indigo-950 h-12 w-full md:w-auto px-8 rounded-xl font-semibold inline-flex items-center justify-center gap-2 mt-8" >
                        <span>View Live Site</span>
                        <ArrowUpRightIcon className="size-4" />
                      </button>
                    </motion.a>
                  </div>
                  <div className="lg:relative">
                    <Image 
                      src={project.image ? getImageUrl(project.image.url) : getImageUrl('/uploads/placeholder.jpg')}
                      alt={project.title} 
                      width={project.image?.width || 800}
                      height={project.image?.height || 600}
                      className="mt-8 -mb-4 md:-mb-0 lg:mt-0 lg:absolute lg:h-full lg:w-auto lg:max-w-none" 
                    />
                  </div>
                </div>
              </Card>
            </motion.div>
          ))}
        </div>
      </div>
    </section>
  );
};
